package tech.aistar.controller.personal;

import com.alipay.api.AlipayConstants;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import tech.aistar.AlipayClient;
import tech.aistar.entity.adopt.AdoptApplication;
import tech.aistar.entity.adopt.AdoptCat;
import tech.aistar.entity.adopt.Collect;
import tech.aistar.entity.adopt.UserAddress;
import tech.aistar.entity.foster.Foster;
import tech.aistar.entity.foster.Replay;
import tech.aistar.entity.personal.*;
import tech.aistar.pay.alipay.core.AlipayCore;
import tech.aistar.pay.alipay.entity.request.AlipayWebSiteRequest;
import tech.aistar.service.adopt.IAdoptApplicationService;
import tech.aistar.service.adopt.IAdoptCatService;
import tech.aistar.service.adopt.ICollectService;
import tech.aistar.service.adopt.IUserAddressService;
import tech.aistar.service.foster.IFosterService;
import tech.aistar.service.foster.IReplayService;
import tech.aistar.service.mycat.ICatService;
import tech.aistar.service.personal.IOrderCommentService;
import tech.aistar.service.personal.IPurchaseService;
import tech.aistar.service.personal.IUserInfoService;
import tech.aistar.service.personal.IUserService;
import tech.aistar.utill.DateUtil;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Created by LJX on 2019/9/25.
 */
@Controller
@Transactional
@RequestMapping("/personal")
public class PersonalController {
    @Autowired
    private IUserService iUserService;

    @Autowired
    private IUserInfoService iUserInfoService;

    @Autowired
    private IPurchaseService iPurchaseService;

    @Autowired
    private IOrderCommentService iOrderCommentService;

    @Autowired
    private IFosterService iFosterService;

    @Autowired
    private IAdoptApplicationService iAdoptApplicationService;

    @Autowired
    private IUserAddressService iUserAddressService;

    @Autowired
    private IReplayService replayService;

    @Autowired
    private ICollectService collectService;

    @Autowired
    private ICatService catService;

    @Autowired
    private IAdoptCatService adoptCatService;


    //跳转个人中心页面
    @RequestMapping("/personalCenterView")
    public String personalCenter(HttpServletRequest req, Model model) {
        User user = (User) req.getSession().getAttribute("user");
        //从个人信息中获取头像信息
        UserInfo userInfo = iUserInfoService.findById(user.getId());
        //获取收藏数量 --Cat
//        List<Collect> collects = collectService.findById(user.getId());
        //封装到 第三方实体类
//        List<CatCollect> cats = new ArrayList<>();
//
//        for (Collect c : collects) {
//            if (catService.findById(c.getCatId()) != null) {
//                if (c.getStatus() == 0) {
//                    CatCollect collect = new CatCollect();
//                    collect.setAddTime(c.getAddTime());
//                    collect.setCat(catService.findById(c.getCatId()));
//                    collect.setCatPrice(adoptCatService.findOneById(c.getCatId()).getCatPrice());
//                    collect.setIntroduction(adoptCatService.findOneById(c.getCatId()).getIntroduction());
//                    collect.setStatus(c.getStatus());
//                    cats.add(collect);
//                }
//            }
//        }
//        req.getSession().setAttribute("cats", cats);
//        model.addAttribute("cats", cats);
        String toId = String.valueOf(user.getId());
        List<Replay> replays = replayService.findByToId(toId);
        model.addAttribute("userInfo", userInfo);
        model.addAttribute("replays", replays);
        return "personal/personalcenterMyComment";

    }

    //获取个人设置--基本信息
    @RequestMapping("personalSettingList")
    public String personalSettingList(Model model, HttpServletRequest req, HttpServletResponse resp) {
        User user = (User) req.getSession().getAttribute("user");
        UserInfo userInfo = iUserInfoService.findById(user.getId());
        List<Collect> collects = collectService.findById(user.getId());
//        List<CatCollect> cats = (List<CatCollect>) req.getSession().getAttribute("cats");
//        model.addAttribute(cats);
        model.addAttribute("collects", collects);
        if (userInfo.getBirthday() != null) {
            String birthday = DateUtil.dateFormat2(userInfo.getBirthday());
            model.addAttribute("birthday", birthday);
        } else {
            String birthday = "";
            model.addAttribute("birthday", birthday);
        }
        System.out.println(userInfo);
        if (user.getId().equals(userInfo.getId())) {
            req.getSession().setAttribute("user", user);
            req.getSession().setAttribute("userInfo", userInfo);
            return "personal/personalcenterSetting";
        } else {
            return "personal/personalcenterSetting?error=0";
        }

    }

    //更改个人信息
    @RequestMapping("personalSettingListUpdate")
    public String personalSettingListUpdate(HttpServletRequest req, String nickname, Date birthday, String useremail, String address, String phone, HttpServletResponse resp) {
        User user = (User) req.getSession().getAttribute("user");
        String gender = req.getParameter("gender");
        UserInfo userInfo = iUserInfoService.findById(user.getId());
        userInfo.setNickname(nickname);
        userInfo.setAddress(address);
        userInfo.setPhone(phone);
        userInfo.setUseremail(useremail);
        userInfo.setBirthday(birthday);

        if (gender.equals("女")) {
            userInfo.setGender(0);
        }
        if (gender.equals("男")) {
            userInfo.setGender(1);
        }
//        else {
//            userInfo.setGender(1);
//        }
        iUserInfoService.updateById(userInfo);
        req.getSession().setAttribute("userInfo", userInfo);
//        return "/personal/personalcenterSetting";
        return "forward:personalSettingList";
    }

    //跳转收货地址页面
    @RequestMapping("personalCenterMyAddressView")
    public String personalCenterMyAddress(HttpServletRequest req, Model model) {
        User user = (User) req.getSession().getAttribute("user");
        //根据id查找用户个人详细信息
        UserInfo userInfo = iUserInfoService.findById(user.getId());
        List<Collect> collects = collectService.findById(user.getId());
        model.addAttribute("collects", collects);
        //根据userId查找用户地址
        List<UserAddress> userAddresses = iUserAddressService.findById(user.getId());
        model.addAttribute("userAddresses", userAddresses);
        model.addAttribute("userInfo", userInfo);
        return "personal/personalcenterMyAddress";
    }

    //收获地址设为默认 1
    @RequestMapping("personalCenterMyAddressisdefault")
    public String personalCenterMyAddressisdefault(Integer id) {
        iUserAddressService.setDefault(id);
        return "redirect:personalCenterMyAddressView";
    }

    //收获地址设为默认 0
    @RequestMapping(
            "personalCenterMyAddressisdefault1")
    public String personalCenterMyAddressisdefault1(Integer id) {
        iUserAddressService.setDefault1(id);
        return "redirect:personalCenterMyAddressView";
    }

    //修改我的收获地址
    @RequestMapping("personalCenterMyAddressupdate")
    public String personalCenterMyAddressupdate(Model model, HttpServletRequest req) {
        //获取表单中的内容
        String uid = req.getParameter("id");
        Integer id = Integer.valueOf(uid);
        String userName = req.getParameter("userName");
        String userPhone = req.getParameter("userPhone");
        String provinceName = req.getParameter("provinceName");
        String cityName = req.getParameter("cityName");
        String areaName = req.getParameter("areaName");
        String detailAddress = req.getParameter("detailAddress");
        String name = req.getParameter("name");
        UserAddress userAddress = iUserAddressService.findId(id);

        userAddress.setUserName(userName);
        userAddress.setUserPhone(userPhone);
        userAddress.setProvinceName(provinceName);
        userAddress.setCityName(cityName);
        userAddress.setAreaName(areaName);
        userAddress.setDetailAddress(detailAddress);
        userAddress.setName(name);
        iUserAddressService.update(userAddress);
        req.getSession().setAttribute("userAddress", userAddress);
        model.addAttribute("userAddress", userAddress);
        return "redirect:personalCenterMyAddressView";

    }

    //添加收货地址
    @RequestMapping("personalCenterMyAddressSave")
    public String personalCenterMyAddressSave(HttpServletRequest req) {
        User user = (User) req.getSession().getAttribute("user");
        String userName1 = req.getParameter("userName1");
        String userPhone1 = req.getParameter("userPhone1");
        String provinceName1 = req.getParameter("provinceName1");
        String cityName1 = req.getParameter("cityName1");
        String areaName1 = req.getParameter("areaName1");
        String detailAddress1 = req.getParameter("detailAddress1");
        String name1 = req.getParameter("name1");
        UserAddress userAddress = new UserAddress();
        userAddress.setUserName(userName1);
        userAddress.setUserPhone(userPhone1);
        userAddress.setDetailAddress(detailAddress1);
        userAddress.setProvinceName(provinceName1);
        userAddress.setCityName(cityName1);
        userAddress.setAreaName(areaName1);
        userAddress.setName(name1);

        userAddress.setUserId(user.getId());
        iUserAddressService.save(userAddress);
        return "forward:personalCenterMyAddressView";
    }

    //删除我的收获地址
    @RequestMapping("personalCenterMyAddressDel")
    public String personalCenterMyAddressDel(Integer id) {
        iUserAddressService.delId(id);
        return "redirect:personalCenterMyAddressView";
    }

    //跳转订单页面
    @RequestMapping("personalCenterMyOrderView")
    public String personalCenterMyOrder(Model model, HttpServletRequest req) {
        User user = (User) req.getSession().getAttribute("user");
        List<Purchase> purchases = iPurchaseService.findByuserId(user.getId());
        UserInfo userInfo = iUserInfoService.findById(user.getId());
        model.addAttribute("userInfo", userInfo);
        List<Collect> collects = collectService.findById(user.getId());
//        for(Purchase p:purchases){
//                    Foster foster = iFosterService.findByOrderId(p.getId());
//        }
//        Foster foster = iFosterService.findByOrderId();

        model.addAttribute("collects", collects);

        model.addAttribute("purchases", purchases);
        return "personal/personalcenterMyOrder";
    }

    //改变订单状态
    @RequestMapping("personalCenterMyOrderViewpayment")
    public String payment(Model model, String purseId) {
        System.out.println(purseId);

        iPurchaseService.updatePayment(Integer.valueOf(purseId));
        return "forward:" +
                "personalCenterMyOrderView";
    }

    //取消订单
    @RequestMapping("personalCenterMyOrdercancelList")
    public String personalCenterMyOrdercancelList(Integer id) {
        if (iPurchaseService.findById(id).getOrdertype() == 1) {
            AdoptApplication adoptApplication = iAdoptApplicationService.findOneById(id);
            adoptCatService.updateStatus(adoptApplication.getCatId());
        }
        iPurchaseService.updateOrdercancel(id);
        return "redirect:personalCenterMyOrderView";
    }

    //删除单个订单
    @RequestMapping("personalMyOrderDel")
    public String personalMyOrderDel(Model model, Integer id, User user, Purchase purchase) {
        iPurchaseService.update(id);
        return "redirect:personalCenterMyOrderView";
    }

    //批量删除选中订单
    @RequestMapping("/del")
    public String delAny(HttpServletResponse resp, HttpServletRequest req) {
        String[] ids = req.getParameterValues("id");
        for (String s : ids) {
            iPurchaseService.update(Integer.valueOf(s));
        }
        return "redirect:personalCenterMyOrderView";
    }

    //跳转订单详情页面
    @RequestMapping("personalMyOrderDeatilsView")

    public String personalMyOrderDetatils(Model model, HttpServletRequest req, HttpServletResponse resp, Integer id) {
        User user = (User) req.getSession().getAttribute("user");
        UserInfo userInfo = iUserInfoService.findById(user.getId());
        model.addAttribute("userInfo", userInfo);
        //根据id查找订单信息
        Purchase purchase = iPurchaseService.findById(id);
//        req.getSession().setAttribute("purchase", purchase);

        //根据订单id查找订单评论信息
        OrderComment orderComment = iOrderCommentService.findByOrderId(id);
        //根据订单id查找寄养信息
        Foster foster = iFosterService.findByOrderId(id);

        model.addAttribute("foster", foster);
        List<Collect> collects = collectService.findById(user.getId());
        model.addAttribute("collects", collects);

        //根据订单id查看领养信息
        AdoptApplication adoptApplication = iAdoptApplicationService.findOneById(id);
        //根据猫id查找


//        Purchase purchase1 = (Purchase) req.getSession().getAttribute("purchase");
        if (purchase.getOrdertype() == 0) {
            String startTime = DateUtil.dateFormat2(foster.getStartTime());
            String endTime = DateUtil.dateFormat2(foster.getEndTime());
            String time = DateUtil.dateFormat(purchase.getTime());
            model.addAttribute("startTime", startTime);
            model.addAttribute("endTime", endTime);
            model.addAttribute("time", time);
        }
        if (purchase.getOrdertype() == 1) {
            String time = DateUtil.dateFormat(purchase.getTime());
            String data = DateUtil.dateFormat(adoptApplication.getDate());
            model.addAttribute("time", time);
            model.addAttribute("data", data);
            AdoptCat adoptCat = adoptCatService.findOneById(adoptApplication.getCatId());
            model.addAttribute("adoptCat",adoptCat);
        }
        req.getSession().setAttribute("purchase", purchase);
        model.addAttribute("adoptApplication", adoptApplication);
        model.addAttribute("orderComment", orderComment);
        model.addAttribute("purchase", purchase);

        return "personal/personalMyorderDetails";
    }

    //订单评论信息
    @RequestMapping("personalMyOrderCommentList")
    public String personalMyorderCommentList(Model model, HttpServletRequest req, Integer id) {
        System.out.println(id);
        OrderComment orderComment = new OrderComment();

        User user = (User) req.getSession().getAttribute("user");
//        Purchase purchase = (Purchase) req.getSession().getAttribute("purchase");

        orderComment.setOrderId(id);
        orderComment.setUserId(user.getId());
        String content = req.getParameter("content");
        orderComment.setContent(content);
        orderComment.setStatus(0);
        orderComment.setOrderTime(new Date());
        iOrderCommentService.save(orderComment);

        req.getSession().setAttribute("orderComment", orderComment);

        return "forward:personalMyOrderDeatilsView?id=" + id;
    }

    //个人中心---头像上传
    @RequestMapping("img")
    public String upload(HttpServletRequest req, Model model) {
        String avatar = req.getParameter("avatar");
        System.out.println(avatar);
        User user = (User) req.getSession().getAttribute("user");

        UserInfo userInfo = iUserInfoService.findById(user.getId());
        userInfo.setAvatar(avatar);
        iUserInfoService.uploadById(userInfo);
        req.getSession().setAttribute("userInfo", userInfo);
        System.out.println(userInfo);
        return "forward:personalCenterView";
    }

    //跳转我的收藏
    @RequestMapping("collect")
    public String collect(Model model, HttpServletRequest req) {
        User user = (User) req.getSession().getAttribute("user");
        UserInfo userInfo = iUserInfoService.findById(user.getId());

        List<Collect> collects = collectService.findById(user.getId());
        System.out.println("Collects:" + collects);
        List<CatCollect> cats = new ArrayList<>();

        for (Collect c : collects) {
            if (catService.findById(c.getCatId()) != null) {
                if (c.getStatus() == 0) {
                    CatCollect collect = new CatCollect();
                    String time = DateUtil.dateFormat(c.getAddTime());
                    model.addAttribute("time",time);
                    collect.setAddTime(c.getAddTime());
                    collect.setCat(catService.findById(c.getCatId()));
                    collect.setCatPrice(adoptCatService.findOneById(c.getCatId()).getCatPrice());
                    collect.setIntroduction(adoptCatService.findOneById(c.getCatId()).getIntroduction());
                    collect.setStatus(c.getStatus());
                    collect.setImgUrl(adoptCatService.findOneById(c.getCatId()).getImgUrl());
                    cats.add(collect);
                }
            }
        }

        model.addAttribute("cats", cats);
        req.getSession().setAttribute("cats", cats);
        model.addAttribute("collects", collects);
        model.addAttribute("userInfo", userInfo);


        return "personal/personalcenterMyCollect";
    }

    //取消收藏状态
    @RequestMapping("collectdel")
    public String collectdel(Model model, HttpServletRequest req) {
        User user = (User) req.getSession().getAttribute("user");
        String[] ids = req.getParameterValues("id");

        for (String s : ids) {
            collectService.delById(Integer.valueOf(s), user.getId());
        }
//        collectService.delById(id,user.getId());
        List<Collect> collects = collectService.findById(user.getId());
        System.out.println("Collects:" + collects);
        return "redirect:collect";
    }


    @InitBinder
    public void initBinder(WebDataBinder binder) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        dateFormat.setLenient(false);
        binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
    }
}
